package com.ruoyi.file.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ruoyi.file.service.ISysFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.UUID;

@Service
@Primary
public class AlyOssFileServiceImpl implements ISysFileService {

    @Value("${alYunOss.endpoint}")
    private String ALIYUN_OSS_ENDPOINT;

    @Value("${alYunOss.accessKey}")
    private String ALIYUN_OSS_ACCESSKEYID;

    @Value("${alYunOss.secretKey}")
    private String ALIYUN_OSS_ACCESSKEYSECRET;

    @Value("${alYunOss.bucketName}")
    private String ALIYUN_OSS_BUCKETNAME;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(ALIYUN_OSS_ENDPOINT, ALIYUN_OSS_ACCESSKEYID, ALIYUN_OSS_ACCESSKEYSECRET);

            // 获取文件名
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                throw new IllegalArgumentException("文件名为空");
            }
            // 获取文件后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            // 最后上传生成的文件名
            String finalFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 7) + suffixName;
            // 文件上传
            ossClient.putObject(ALIYUN_OSS_BUCKETNAME, finalFileName, new ByteArrayInputStream(file.getBytes()));

            // 构建文件访问 URL
            String url = String.format("%s://%s.%s/%s",
                    ALIYUN_OSS_ENDPOINT.startsWith("https") ? "https" : "http",
                    ALIYUN_OSS_BUCKETNAME,
                    ALIYUN_OSS_ENDPOINT.replaceFirst("http[s]?://", ""),
                    finalFileName);

            System.out.println("阿里云==" + url);
            return url;
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            throw new RuntimeException("文件上传失败", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
